/* eslint-disable array-callback-return */
import React, { Component } from 'react';
import ClickItem from '../verifyTelephoneModal/ClickItem';
import CountryCodeList from './countryCodeList/CountryCodeList';
import fangg from './fangg.json';
import './css/verifyTelephone.less';

const API = WPT.Util.handleApi({
    sendCode: '/v1.0/telephone/',
    codeVerifyUrl: '/v1.0/telephone/to-update-tel-l',
    telephoneVerifyUrl: '/v1.0/telephone/verify-tel-l',
});
export default class VerifyTelephone extends Component {
    state = {
        isHide: true, // 默认隐藏电话验证组件
        secretCodeBox: false, // 默认验证为关
        verifyTelephone: '', // 验证的电话号码
        verifyTelephoneTime: 60, // 60秒
        checkTypeObj: 'sms', // 当前正在验证类型
        secretCode: '', // 验证码
        checkType: ['sms', 'call'],
        title: '请输入您的电话号码',
        tipsText: '',
        confirmBtnTxt: '下一步',
        verifyTelephoneType: 'my', // 认证入口   verifyTelephoneType + /verify_telephone_return
        telephoneVerifyUrl: API.telephoneVerifyUrl, // 验证电话号码
        sendCodeUrl: API.sendCode, // 发送 验证码
        codeVerifyUrl: API.codeVerifyUrl, // 验证 验证码
        num: [
            { num: 1 },
            { num: 2, letter: 'ABC' },
            { num: 3, letter: 'DEF' },
            { num: 4, letter: 'GHI' },
            { num: 5, letter: 'JKL' },
            { num: 6, letter: 'MNO' },
            { num: 7, letter: 'PQRS' },
            { num: 8, letter: 'TUV' },
            { num: 9, letter: 'WXYZ' },
        ],
        sms: {
            // 短信验证的按钮
            keyDown: false, // 是否变灰
            txt: '短信验证', // 按钮文案
            isShow: true, // 按钮是否显示
        },
        call: {
            keyDown: false,
            txt: '点击进行语音验证',
            isShow: true,
        },
        ServiceTel: '0571-81110039',
        checkResult: '', // 验证完后提示信息
        callback: '', // 验证完后的回调函数
        showCountryCode: false, // 是否显示国家区号页面
        country: 'CN', // 默认中国
        countryCode: '86', // 默认中国区号
        pattern: '^(86){0,1}1\\d{10}$', // 默认中国手机号校验
        ajaxParam: {},
    };

    componentDidMount = () => {
        $(document).on('keydown', e => {
            if (this.state.isHide) {
                return;
            }
            if (e.keyCode == '8') {
                // Backspace  delete
                this.delete();
            }
            if (e.keyCode >= 48 && e.keyCode <= 57) {
                this.input(e.keyCode - 48);
            }
            if (e.keyCode >= 96 && e.keyCode <= 105) {
                this.input(e.keyCode - 96);
            }
        });
    };

    componentWillUnmount() {
        WPT.Interval.clear('verifyTelephone');
        $(document).off('keyup');
    }

    show = data => {
        this.state.isHide = data.isHide;
        if (!$.isEmptyObject(this.state.errList)) {
            // 错误的时候初始化下
            this.state.verifyTelephone = '';
            this.state.checkTypeObj = 'sms'; // 当前正在验证类型state.secretCode = '';   //验证码
            this.state.checkType = ['sms', 'call'];
            this.state.tipsText = '';
            this.state.confirmBtnTxt = '下一步';
            this.state.verifyTelephoneType = 'my'; // 认证入口   verifyTelephoneType + /verify_telephone_return
            this.state.sms = {
                // 短信验证的按钮
                keyDown: false, // 是否变灰
                txt: '短信验证', // 按钮文案
                isShow: true, // 按钮是否显示
            };
            this.state.call = {
                keyDown: false,
                txt: '语音验证',
                isShow: true,
            };
            this.state.checkResult = ''; // 验证完后提示信息
        }
        if (data.checkType && this.state.checkType.length != 1) {
            // 国外手机号没有语音验证，lengh为1
            this.state.checkType = data.checkType;
            // eslint-disable-next-line prefer-destructuring
            this.state.checkTypeObj = data.checkType[0];
        }

        if (data.verifyTelephone && this.state.secretCodeBox === false) {
            // 已在验证阶段不需要更新state
            if (data.verifyTelephone.indexOf('-') !== -1) {
                const strTel = data.verifyTelephone.split('-');
                Object.keys(fangg).map(letter => {
                    fangg[letter].map(i => {
                        if (i.code === strTel[0]) {
                            this.setState({
                                country: i.abbreviation,
                                countryCode: i.code,
                                pattern: i.pattern,
                                verifyTelephone: strTel[1],
                                checkType: ['sms'],
                            });
                        }
                    });
                });
            } else {
                this.state.verifyTelephone = data.verifyTelephone.replace(/(\d{3})-?(\d{4})-?(\d{1,4}).*/, '$1-$2-$3');
                this.setState({
                    country: 'CN',
                    countryCode: '86',
                    pattern: '^(86){0,1}1\\d{10}$',
                });
            }
        } else if (!data.verifyTelephone && this.state.secretCodeBox === false) {
            // 没有绑定过电话号码默认验证国内
            this.setState({
                country: 'CN',
                countryCode: '86',
                pattern: '^(86){0,1}1\\d{10}$',
            });
        }

        this.state.ajaxParam = data.ajaxParam || {};
        data.title && (this.state.title = data.title);
        this.state.tipsText = this.state.tipsText || data.tipsText || '完善您的联系方式';

        data.sendCodeUrl && (this.state.sendCodeUrl = data.sendCodeUrl);
        data.codeVerifyUrl && (this.state.codeVerifyUrl = data.codeVerifyUrl);
        data.telephoneVerifyUrl && (this.state.telephoneVerifyUrl = data.telephoneVerifyUrl);
        this.state.errList = [];
        data.verifyTelephoneType && (this.state.verifyTelephoneType = data.verifyTelephoneType);
        data.ServiceTel && (this.state.ServiceTel = data.ServiceTel);
        this.setState({
            callback: data.callback,
        });
    };

    hide = () => {
        this.setState({
            isHide: true,
        });
    };

    operatorsTel = [
        '1700',
        '1701',
        '1702',
        '1703',
        '1705',
        '1706,1704',
        '1707',
        '1708',
        '1709',
        '1710',
        '1711',
        '1712',
        '1713',
        '1714',
        '1715',
        '1716',
        '1717',
        '1718',
        '1719',
    ];

    format = num => {
        num = num.replace(/[\D]/g, '');
        if (!this.state.secretCodeBox) {
            if (this.state.country === 'CN') {
                // 仅限中国手机号码
                num = num.replace(/(\d{3})-?(\d{4})-?(\d{1,4}).*/, '$1-$2-$3');
            }
        } else {
            num = num.substr(0, 4);
        }
        return num;
    };

    // 正则校验手机号码
    check = t => {
        const _emp = /^\s*|\s*$/g;
        const _reg = new RegExp(this.state.pattern);
        t = `${this.state.countryCode}${t.replace(_emp, '')}`; // 校验时拼上国家区号
        if (_reg.test(t)) {
            return 1;
        }
        return 0;
    };

    input = num => {
        if (!this.state.secretCodeBox) {
            this.state.verifyTelephone = this.format(`${this.state.verifyTelephone}${num}`);
        } else {
            this.state.secretCode = this.format(`${this.state.secretCode}${num}`);
        }
        this.forceUpdate();
    };

    // 发送短信或者呼叫电话号码  进行验证
    sendCode = type => {
        // const self = this;
        const state = this.state;
        const obj = this.state[type];
        if (this.state[type] == undefined || this.state[type].keyDown) {
            return;
        }

        state.checkTypeObj = type;
        obj.keyDown = true;
        state.verifyTelephoneTime = 60;
        // eslint-disable-next-line no-plusplus
        obj.txt = `${--state.verifyTelephoneTime} 秒后可重新获取`;
        if (state.checkType.length == 2) {
            if (type == 'sms') {
                state.call.isShow = false;
            } else if (type == 'call') {
                state.sms.isShow = false;
            }
        }
        this.forceUpdate();
        WPT.Interval.append('verifyTelephone', () => {
            // var verifyTelephoneTime = --state.verifyTelephoneTime;
            state.verifyTelephoneTime -= 1;
            state[state.checkTypeObj].txt = `${state.verifyTelephoneTime} 秒后可重新获取`;
            if (state.verifyTelephoneTime <= 0) {
                WPT.Interval.clear('verifyTelephone');
                state[state.checkTypeObj].txt = state.checkTypeObj == 'sms' ? '短信验证' : '语音验证';
                state[state.checkTypeObj].keyDown = false;
                if (state.checkType.length == 2) {
                    if (state.checkTypeObj == 'sms') {
                        state.call.isShow = true;
                    } else if (state.checkTypeObj == 'call') {
                        state.sms.isShow = true;
                    }
                }
            }
            this.forceUpdate();
        });

        const telephone = state.verifyTelephone.replace(/-/g, '');
        WPT.getData(
            state.sendCodeUrl + type,
            {
                tel: telephone,
                nationCode: this.state.countryCode,
                type,
            },
            res => {
                this.setState({ tipsText: 'ArtificialValidation' });
                const code = res.errcode || res.code;
                const msg = res.errmsg || res.msg;
                if (code == 0) {
                    this.setState({
                        secretCodeBox: true,
                        confirmBtnTxt: '确认',
                        secretCode: '',
                    });
                } else if (code == 1000) {
                    WPT.Modal.alert(`${msg}60秒后请重新再试`);
                    return false;
                } else if (code > 0) {
                    WPT.Modal.alert(msg);
                    return false;
                }
                return null;
            }
        );
    };

    submit = () => {
        const state = this.state;
        state.checkResult = '';
        const telephone = state.verifyTelephone.replace(/-/g, '');
        const nationCode = state.countryCode;

        if (!state.secretCodeBox) {
            if (this.check(telephone) == 0) {
                this.setState({
                    checkResult: '电话号码有误',
                });
                return false;
            }
            WPT.Interval.clear('verifyTelephone'); // todo
            // 检查电话号码
            const ajaxParam = $.extend(state.ajaxParam, { tel: telephone, nationCode });

            WPT.postData(state.telephoneVerifyUrl, ajaxParam, res => {
                if (res.errcode == 0 || res.code == 0) {
                    if (nationCode != '86') {
                        // 国际
                        state.checkTypeObj = 'sms';
                        state.checkType = ['sms'];
                    }
                    if (this.operatorsTel.indexOf(telephone.slice(0, 4)) != -1) {
                        this.state.checkTypeObj = 'call';
                        this.state.checkType = ['call'];
                    }
                    this.state.checkResult = '';
                    this.state.secretCodeBox = true;
                    this.state.confirmBtnTxt = '确认';
                    this.sendCode(state.checkTypeObj);
                } else {
                    this.setState({
                        checkResult: res.errmsg || res.msg,
                    });
                }
            });
        } else {
            if (state.secretCode.length != 4) {
                this.setState({
                    checkResult: '验证码错误',
                });
                return false;
            }

            WPT.postData(
                state.codeVerifyUrl,
                {
                    tel: telephone,
                    code: state.secretCode,
                    nationCode,
                },
                res => {
                    if (res.errcode == 0 || res.code == 0) {
                        if (res.data && res.data.errorList) {
                            this.setState({
                                errList: res.data.errorList,
                                secretCodeBox: false, // 默认验证为关
                            });
                        } else {
                            // 电话验证通过
                            WPT.userinfo.hasTelephone = 88888888888;
                            WPT.userinfo.isSubscribe = 2;
                            this.setState({
                                secretCodeBox: false,
                                secretCode: '',
                                sms: {
                                    // 短信验证的按钮
                                    keyDown: false, // 是否变灰
                                    txt: '短信验证', // 按钮文案
                                    isShow: true, // 按钮是否显示
                                },
                                call: {
                                    keyDown: false,
                                    txt: '语音验证',
                                    isShow: true,
                                },
                            });
                            this.hide();
                            // self.props.handleIsHide();
                            typeof state.callback === 'function'
                                && state.callback(nationCode != '86' ? `${nationCode}-${telephone}` : telephone, res);
                        }
                    } else {
                        state.checkResult = res.errmsg || res.msg;
                    }
                    this.forceUpdate();
                }
            );
        }
        return null;
    };

    GOArtificialValidation = () => {
        this.setState({
            tipsText: 'GOArtificialValidation',
        });
    };

    setShowCountrycodeList = (value = true) => {
        // 控制显示“选择国家”组件
        this.setState({
            showCountryCode: value,
        });
    };

    setCountryInfo = (country, countryCode, pattern) => {
        // 选择区号组件的回调函数
        this.setState({
            checkType: country !== 'CN' ? ['sms'] : ['sms', 'call'],
            country,
            countryCode,
            pattern,
        });
    };

    formatVerifyTelephone = () => {
        // 国内手机号格式化 // 从选择区号页面返回时调用
        this.state.verifyTelephone && this.state.country === 'CN'
            ? this.setState({
                verifyTelephone: this.state.verifyTelephone
                    .replace(/-/g, '')
                    .replace(/(\d{3})-?(\d{4})-?(\d{1,4}).*/, '$1-$2-$3'),
            })
            : this.setState({
                verifyTelephone: this.state.verifyTelephone.replace(/-/g, ''),
            });
    };

    delete = () => {
        if (!this.state.secretCodeBox) {
            this.state.verifyTelephone = this.format(
                this.state.verifyTelephone.substr(0, this.state.verifyTelephone.length - 1)
            );
        } else {
            this.state.secretCode = this.format(this.state.secretCode.substr(0, this.state.secretCode.length - 1));
        }
        this.forceUpdate();
    };

    render() {
        const state = this.state;
        if (state.isHide) {
            return null;
        }
        return (
            <div className="verifyTelephoneMain">
                <div className="wptMask" {...WPT.onTouchEnd(this.hide, 0)} />
                {state.showCountryCode && (
                    <CountryCodeList
                        setCountryInfo={this.setCountryInfo}
                        setShowCountrycodeList={this.setShowCountrycodeList}
                        formatVerifyTelephone={this.formatVerifyTelephone}
                    />
                )}
                <div className={`verifyMain flip-up ${$.isEmptyObject(state.errList) ? '' : ' hide'}`}>
                    {!state.secretCodeBox ? (
                        <div className="telephoneBox">
                            <div className="title" dangerouslySetInnerHTML={{ __html: state.title }} />
                            <div className="telephoneInput">
                                <div className="countryCodeButton" onClick={this.setShowCountrycodeList}>
                                    {`${state.country} +${state.countryCode}`}
                                </div>
                                <div className="separater" />
                                <span className={`hover ${!state.verifyTelephone ? '' : ' hasValue'}`}>
                                    {state.verifyTelephone}
                                </span>
                            </div>
                        </div>
                    ) : (
                        <div className="secretCodeBox">
                            <div className="title">
                                {state.checkTypeObj == 'sms' ? (
                                    <div>
                                        <span className="darkRed">验证码</span>
                                        <span className="darkRed">已发送至</span>
                                        <span className="darkRed telephone">{state.verifyTelephone}</span>
                                    </div>
                                ) : (
                                    <div>
                                        <span className="darkRed">验证码</span>
                                        已发送至
                                        <span className="darkRed telephone">{state.verifyTelephone}</span>
                                    </div>
                                )}
                            </div>
                            {state.checkTypeObj == 'call' && (
                                <div className="callNotice">我们将在1分钟内给您来电，请及时接听</div>
                            )}
                            <div className="secretCode">
                                <div className="secretCodeInput">
                                    <span className={`hover ${!state.verifyTelephone ? '' : 'hasValue'}`}>
                                        {state.secretCode}
                                    </span>
                                </div>
                                <div className="checkBtnBanner">
                                    {state.checkType.indexOf('sms') > -1 && (
                                        <div
                                            className={`btn smsCheck ${state.sms.keyDown ? ' keyDown' : ''}
                                                    ${state.sms.isShow ? '' : ' none'}`}
                                            {...WPT.onTouchEnd(this.sendCode.bind(this, 'sms'), 1)}
                                        >
                                            {state.sms.txt}
                                        </div>
                                    )}
                                    {state.checkType.indexOf('call') > -1 && (
                                        <div
                                            className={`btn callCheck ${state.call.keyDown ? ' keyDown' : ''} ${
                                                state.call.isShow ? '' : ' none'
                                            }`}
                                            {...WPT.onTouchEnd(this.sendCode.bind(this, 'call'), 1)}
                                        >
                                            {state.call.txt}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="tips">
                        <div className="checkResult">{state.checkResult}</div>
                        <div className="tipText">
                            {state.tipsText == 'GOArtificialValidation' ? (
                                <div>
                                    请拨
                                    {' '}
                                    <a href={state.ServiceTel ? `tel:${state.ServiceTel}` : '#'}>{state.ServiceTel}</a>
                                    {' '}
                                    进行人工验证！
                                </div>
                            ) : state.tipsText == 'ArtificialValidation' ? (
                                <span {...WPT.onTouchEnd(this.GOArtificialValidation, 1)}>收不到验证码？</span>
                            ) : (
                                state.tipsText
                            )}
                        </div>
                    </div>

                    <div className="btnBanner">
                        <div className="confirmBtn" {...WPT.onTouchEnd(this.submit, 1)}>
                            {state.confirmBtnTxt}
                        </div>
                    </div>

                    <div
                        className="numkey"
                        onContextMenu={e => {
                            e.preventDefault();
                        }}
                    >
                        <ul>
                            {state.num.map((item, i) => (
                                <ClickItem
                                    key={i}
                                    data-touch="touchEffect"
                                    className="num"
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onClick={this.input.bind(this, item.num)}
                                >
                                    <div className="num">{item.num}</div>
                                    <div className="letter">{item.letter}</div>
                                </ClickItem>
                            ))}
                            <ClickItem data-touch="touchEffect" className="num othernum" onClick={this.hide}>
                                取消
                            </ClickItem>
                            <ClickItem
                                data-touch="touchEffect"
                                className="num"
                                style={{ lineHeight: '50px' }}
                                // eslint-disable-next-line react/jsx-no-bind
                                onClick={this.input.bind(this, 0)}
                            >
                                0
                            </ClickItem>
                            <ClickItem data-touch="touchEffect" className="delete" onClick={this.delete} />
                        </ul>
                    </div>
                </div>
                {
                    <div className={`errBox ${$.isEmptyObject(state.errList) ? ' hide' : ''}`}>
                        <div className="errTitle">
                            <span>当前账户已存在以下数据</span>
                            <br />
                            <span>{`暂时不能与 ${state.verifyTelephone.replace(/-/g, '')} 绑定`}</span>
                        </div>
                        <div className="errContent">
                            {!$.isEmptyObject(state.errList)
                                && state.errList.map((errItem, i) => (
                                    <div key={i} className={`errItem ${errItem.icon}`}>
                                        <div className="itemTitle">
                                            <i className={`wptFM icon-fm-${errItem.icon}`} />
                                            {errItem.name}
                                        </div>
                                        <div className="itemContent">{errItem.value}</div>
                                    </div>
                                ))}
                        </div>
                        <div className="errButton" {...WPT.onTouchEnd(this.hide, 0)}>
                            <button>我知道了</button>
                        </div>
                    </div>
                }
            </div>
        );
    }
}
